package main.utils;

import com.google.protobuf.MessageLite;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import main.bean.Message;
import main.bean.Player;

import java.util.Collection;

/**
 * Created by JinMiao
 * 2019-08-02.
 */
public class GameUtils {
    public static void sendTo(Message message,Player... players){
        MessageLite messageLite = message.getBody();
        byte[] bytes = null;
        int lenth = 0;
        if(messageLite!=null){
            bytes = messageLite.toByteArray();
            lenth = bytes.length;
        }
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.directBuffer(3+lenth);
        byteBuf.writeShort(message.getActionId());
        byteBuf.writeByte(0);
        if(bytes!=null){
            byteBuf.writeBytes(bytes);
        }
        for (Player player : players) {
            player.getUkcp().write(byteBuf);
        }
        byteBuf.release();
    }
    public static void sendTo(Message message, Collection<Player> players){
        MessageLite messageLite = message.getBody();
        byte[] bytes = null;
        int lenth = 0;
        if(messageLite!=null){
            bytes = messageLite.toByteArray();
            lenth = bytes.length;
        }
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.directBuffer(3+lenth);
        byteBuf.writeShort(message.getActionId());
        byteBuf.writeByte(0);
        if(bytes!=null){
            byteBuf.writeBytes(bytes);
        }
        for (Player player : players) {
            player.getUkcp().write(byteBuf);
        }
        byteBuf.release();
    }
}
